using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Threading;

namespace cb0tServer
{
    class UrlTag
    {
        private static Mutex mutex = new Mutex();

        public static String Url = "http://www.sharptricks.net/";
        public static String Tag = "Welcome to sb0t Ares Chat Server";
        public static bool Enabled = false;

        public static void LoadUrlTag()
        {
            if (!File.Exists(sb0t_winGUI.RunOnceFileUpdater.sbotpath + "data/urltag.xml")) return;

            try
            {
                FileStream f = new FileStream(sb0t_winGUI.RunOnceFileUpdater.sbotpath + "data/urltag.xml", FileMode.Open);
                XmlReader xml = XmlReader.Create(new StreamReader(f));

                xml.MoveToContent();
                xml.ReadSubtree().ReadToFollowing("urltag");
                xml.ReadToFollowing("details");
                xml.ReadSubtree().ReadToFollowing("enabled");
                Enabled = bool.Parse(xml.ReadElementContentAsString());
                xml.ReadToFollowing("url");
                Url = Encoding.UTF8.GetString(Convert.FromBase64String(xml.ReadElementContentAsString()));
                xml.ReadToFollowing("tag");
                Tag = Encoding.UTF8.GetString(Convert.FromBase64String(xml.ReadElementContentAsString()));

                xml.Close();
                f.Flush();
                f.Close();
            }
            catch { }
        }

        public static void SaveUrlTag()
        {
            mutex.WaitOne();

            try
            {
                XmlWriterSettings appearance = new XmlWriterSettings();
                appearance.Indent = true;
                XmlWriter xml = XmlWriter.Create(sb0t_winGUI.RunOnceFileUpdater.sbotpath + "data/urltag.xml", appearance);

                xml.WriteStartDocument();
                xml.WriteStartElement("urltag");
                xml.WriteStartElement("details");
                xml.WriteElementString("enabled", Enabled.ToString());
                xml.WriteElementString("url", Convert.ToBase64String(Encoding.UTF8.GetBytes(Url)));
                xml.WriteElementString("tag", Convert.ToBase64String(Encoding.UTF8.GetBytes(Tag)));
                xml.WriteEndElement();
                xml.WriteEndElement();
                xml.WriteEndDocument();
                xml.Flush();
                xml.Close();
            }
            catch { }

            mutex.ReleaseMutex();
        }
    }
}
